const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const path = require('path')

const app = express()
const PORT = 5000

// --- 中间件 ---
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// 让 'uploads' 文件夹中的图片可以通过URL直接访问
app.use('/uploads', express.static(path.join(__dirname, 'uploads')))

// --- 数据库连接 ---
// !!请将这里的 myProductDatabase 换成你自己的数据库名!!
// const MONGO_URI = 'mongodb://192.168.1.4:27017/myProductDatabase';
const MONGO_URI =
  'mongodb+srv://root:0113@cluster0.6nyw3we.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0'
mongoose
  .connect(MONGO_URI)
  .then(() => console.log('MongoDB 连接成功'))
  .catch((err) => console.error('MongoDB 连接失败:', err))

// --- 路由 ---
app.use('/api/categories', require('./routes/categories'))
app.use('/api/upload', require('./routes/upload'))

// --- 启动服务器 ---
app.listen(PORT, () => {
  console.log(`后台服务已启动，端口号:${PORT}`)
})
